package ws
import (
	// "nightowl/logger"
	"sync"
	"github.com/gorilla/websocket"
)

type LogClient struct {
	ID     string
	Conn   *websocket.Conn
	Send   chan []byte
	LogReader *StepRunLogReader
}

type LogClientManager struct {
	clients    map[string]*LogClient
	clientsMu  sync.RWMutex
	register   chan *LogClient
	unregister chan *LogClient
}

func NewLogClientManager() *LogClientManager {
	return &LogClientManager{
		clients:    make(map[string]*LogClient),
		register:   make(chan *LogClient),
		unregister: make(chan *LogClient),
	}
}

func (m *LogClientManager) Start() {
	// for {
	// 	select {
	// 	case client := <-m.register:
	// 		m.clientsMu.Lock()
	// 		// 检查是否已存在相同ClientID的连接
	// 		if existing, ok := m.clients[client.ID]; ok {
	// 			logger.Info("关闭重复ClientID的连接: %s", client.ID)
	// 			existing.LogReader.Stop()
	// 			close(existing.Send)
	// 			existing.Conn.Close()
	// 		}
	// 		m.clients[client.ID] = client
	// 		m.clientsMu.Unlock()
	// 		logger.Info("客户端注册: %s", client.ID)
			
	// 		// 启动日志读取器
	// 		go client.LogReader.ReadLogs(client.Send, client.ID)
			
	// 	case client := <-m.unregister:
	// 		m.clientsMu.Lock()
	// 		if existing, ok := m.clients[client.ID]; ok && existing == client {
	// 			client.LogReader.Stop()
	// 			close(client.Send)
	// 			delete(m.clients, client.ID)
	// 			logger.Info("客户端注销: %s", client.ID)
	// 			existing.LogReader.Stop()
	// 		}
	// 		m.clientsMu.Unlock()
	// 	}
	// }
}

func (m *LogClientManager) ClientCount() int {
	m.clientsMu.RLock()
	defer m.clientsMu.RUnlock()
	return len(m.clients)
}